use std::collections::HashMap;

use serde::Deserialize;
use tera::Tera;

fn default_root() -> String {
    "templates/**/*.html".to_string()
}

#[derive(Debug, Clone, Deserialize)]
pub struct TemplateConfig {
    /// 默认值`templates/**/*.html`
    #[serde(default = "default_root")]
    pub root: String,
    #[serde(default)]
    pub site: HashMap<String, serde_json::Value>,
    #[serde(flatten)]
    pub context: HashMap<String, serde_json::Value>,
}

impl Default for TemplateConfig {
    fn default() -> Self {
        Self {
            root: default_root(),
            site: Default::default(),
            context: Default::default(),
        }
    }
}

impl TemplateConfig {
    pub fn get_tera(&self) -> (tera::Tera, tera::Context) {
        let tera = Tera::new(&self.root).unwrap();
        let mut context = tera::Context::new();
        context.insert("site", &self.site);
        for (k, v) in &self.context {
            context.insert(k, v);
        }
        (tera, context)
    }
}
